// layui 配置
layui.config({
	base: 'js/lay-module/',
}).extend({
	fcInputNumber:'fcInputNumber/fcInputNumber',
	cascader:'cascader/cascader',
})

layui.use(['jquery','element','form','fcInputNumber','util','rate','slider','laydate','layedit','cascader'],function(){
	var $ = layui.jquery,
		element = layui.element,
		form = layui.form,
		fcInputNumber = layui.fcInputNumber,
		util = layui.util,
		rate = layui.rate,
		slider = layui.slider,
		laydate = layui.laydate,
		layedit = layui.layedit,
		cascader = layui.cascader;

	//表单布局总配置
	var FORMCONFIG = {
		"layout":[
			// {
			// 	"label":"",
			// 	"type":"",
			// }
		],
		"config":{
		    "size": "medium",			
		    "labelPosition": "right",
		    "labelWidth": 80,
		    "type":"normal",
		}
	};

	//radio group change
	$('.radiogroup label').click(function(e){
	    if(!$(e.target).is('input')){
	        return;
	    }		
		$(this).addClass('is-active').siblings('label').removeClass('is-active');
		$(this).children('input').prop('checked',true).siblings('label').children('input').prop('checked',false);
	});

	//表单top工具
	util.event('lay-active',{
		json:function() {
			layer.msg('json')
		},
		view:function() {
			layer.msg('view')
		},
		clear:function() {
			$('#form-designer').html('');
			$('#form-designer').next('.empty').show();
			console.log('清空所有组件')
		},
		save:function() {
			console.log(FORMCONFIG.layout.length)
			if(FORMCONFIG.layout.length == 0) {
				layer.msg('请添加表单组件！')
				return false;
			}
		},
	})

	//表单尺寸设置
	$('.radiogroup[filter="formsize"] label').click(function(e){
	    if(!$(e.target).is('input')){
	        return;
	    }
	    var val = $(this).children('input').val();
	    setFormConfig('size',val);
	})

	//标签对齐设置
	$('.radiogroup[filter="formLabelPosition"] label').click(function(e){
	    if(!$(e.target).is('input')){
	        return;
	    }
	    var val = $(this).children('input').val();
	    setFormConfig('labelPosition',val);
	})	

	//inputNumber 输入回调事件，自定义 -- 输入时候触发
	$('.fc-input-number[fc-filter="labelWidth"]').on('input propertychange', function() {
		var val = $(this).val();
		if(val <= 300 && val >=50) {
			getLabelWidth(val);
		}
	})
	getLabelWidth = function(val) {
		if(val) {
			setFormConfig('labelWidth',val);
		}
	}

	//表单风格设置
	form.on('switch(pane)',function(data){
		var val;
		data.elem.checked?val = 'pane':val = 'normal';
		setFormConfig('type',val);
	})

	//表单渲染
	//var _flag = true;
	var formRender = {
		//初始化
		init:function(data) {
			console.log(data.config)
		var	f = $('#form-designer'),
			d = data.config;

			this.setSize(f,d);
			this.setLabelPosition(f,d);
			this.setLabelWidth(f,d);
			this.setType(f,d);
		},
		//设置表单尺寸
		setSize:function(f,d) {
			if(d.size == 'medium') {
				f.removeAttr('size');
			}else{
				f.attr("size", d.size);
			}
		},
		//设置标签对齐
		setLabelPosition:function(f,d) {
			if(d.labelPosition == 'right') {
				f.removeAttr('labelPosition');
				$('[fc-filter="labelWidth"]').prop('disabled',false);
				$('[lay-filter="pane"]').prop('disabled',false);
				fcInputNumber.render();
			}else{
				f.attr("labelPosition", d.labelPosition);
				if(d.labelPosition =='top') {
					form.val('formset',{
						"pane":0
					})
					f.removeClass('layui-form-pane');
					f.find('.layui-input-block').removeAttr('style');
					$('[fc-filter="labelWidth"]').prop('disabled',true);
					$('[lay-filter="pane"]').prop('disabled',true);
					FORMCONFIG["config"].type = 'normal';
				}else{
					$('[fc-filter="labelWidth"]').prop('disabled',false);
					$('[lay-filter="pane"]').prop('disabled',false);
				}
				fcInputNumber.render();
			}
			form.render(null,'formset');
		},
		//设置标签宽度
		setLabelWidth:function(f,d) {
			if(d.labelPosition != 'top') {
				if(d.type == 'pane') {
					f.find('.layui-form-label').css({width:d.labelWidth+'px'});
					f.find('.layui-input-block').css({marginLeft:(Number(d.labelWidth))+'px'});
				}else{
					f.find('.layui-form-label').css({width:d.labelWidth+'px'});
					f.find('.layui-input-block').css({marginLeft:(Number(d.labelWidth)+30)+'px'});
				}
			}
		},
		//设置方框风格
		setType:function(f,d) {
			if(d.type == 'pane' && d.labelPosition != 'top') {
				f.addClass('layui-form-pane');

				// if(_flag) {
				// 	_flag = false;
				// }
			}else{
				f.removeClass('layui-form-pane');
				// if(!_flag){
				// 	_flag = true;
				// }
			}
		},
		//初始化标签宽度
		reset:function(f) {
			f.find('.layui-form-label').css({width:'80px'});
			f.find('.layui-input-block').css({marginLeft:'110px'});
			FORMCONFIG["config"].labelWidth = 80;
			$('[fc-filter="labelWidth"]').val('80');

		},
	}

	//set form json
	function setFormConfig(name,data) {
		FORMCONFIG["config"][name] = data;
		//console.log(FORMCONFIG)
		formRender.init(FORMCONFIG);
	}




	//表单组件list
	function components(id) {
	    var str = "";
	    
	    /*  tool:普通组件工具结构
	     *  toolColumn:栅格布局内部容器工具结构
	     *  toolRow:栅格布局工具结构
	     * */ 
	    var tool = '<div class="tool"><div><a href="javascript:;" lay-components="copy" title="复制"><i class="iconfont">&#xe601;</i></a><a href="javascript:;" lay-components="del" title="删除"><i class="iconfont">&#xe603;</i></a></div></div>'
	    var toolColumn = '<div class="tool hollow"><div><a href="javascript:;" lay-components="copy" title="复制" data-type="column"><i class="iconfont">&#xe601;</i></a><a href="javascript:;" lay-components="del" title="删除" data-type="column"><i class="iconfont">&#xe603;</i></a></div></div>'
	    var toolRow = '<div class="tool hollow"><div><a href="javascript:;" lay-components="copy" title="复制"><i class="iconfont">&#xe601;</i></a><a href="javascript:;" lay-components="del" title="删除"><i class="iconfont">&#xe603;</i></a></div></div>'

	    switch (id) {
	        case "text":
	            //单行文本
	            var element = '<input type="text" class="layui-input" placeholder="单行文本">';
	            str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">单行输入框</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	            break;
	        case "select":
	            //下拉选择
	            var element = '<select><option>请选择</option><option>默认</option></select>';
	            str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">下拉选择</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	            break;
	        case "textarea":
	            //多行文本
	            var element = '<textarea class="layui-textarea" placeholder="多行文本"></textarea>';
	            str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">多行文本</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	            break;
	        case "radio":
	            //单选框
	            var radom = Math.ceil(Math.random() * 100000);
	            var element = '<input type="radio" value="选项一" name="rad' + radom + '" checked title="选项一"><input type="radio" name="rad' + radom + '" value="选项二" title="选项二">';
	            str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">单选</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	            break;
	        case "checkbox":
	            //多选框
	            var element = '<input type="checkbox" name="" lay-skin="primary" title="选项一"><input type="checkbox" name="" lay-skin="primary" title="选项二">';
	            str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">多选</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	            break;
	        case "datetime":
	            //时间
	            var element = '<input type="text" class="layui-input lay-date">';
	            str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">文本</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	            break;
	        case "InputNumber":
	        	//计数器
	        	var element = '<input class="fc-input-number" fc-filter="" />';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">计数器</label><div class="layui-input-block"><div class="v-c">' + element + '</div></div>'+tool+'</div>';
	        	break;
	       	case "switch":
	       		//开关
	       		var element = '<input type="checkbox" name="switch" lay-skin="switch">';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">开关</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "line":
	       		//分割线
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'" style="padding:5px 0;"><hr>'+tool+'</div>';
	        	break;
	       	case "progress":
	       		//进度条
	       		var element = '<div class="layui-progress layui-progress-big" lay-showPercent="yes" style="width:100%;"><div class="layui-progress-bar layui-bg-blue" lay-percent="50%"></div></div>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">进度条</label><div class="layui-input-block"><div class="v-c">' + element + '</div></div>'+tool+'</div>';
	       		break;
	       	case "title":
	       		//标题
	       		var element = '<h3 class="layui-form-title">标题</h3>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'">' + element + tool +'</div>';
	       		break;
	       	case "rate":
	       		//评分
	       		var radom = Math.ceil(Math.random() * 100000);
	       		var element = '<div id="'+radom+'" class="rate"></div>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">评分</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "link":
	       		//超链接
	       		var element = '<a href="" class="link">超链接</a>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">超链接</label><div class="layui-input-block"><div class="layui-form-mid">' + element + '</div></div>'+tool+'</div>';
	       		break;
	       	case "cascader":
	       		//级联选择器
	       		var radom = Math.ceil(Math.random() * 100000);
	       		var element = '<input type="text" id="cascader_'+radom+'" class="layui-input cascader" readonly="readonly">';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">级联选择器</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "slider":
	       		//滑块
	       		var radom = Math.ceil(Math.random() * 100000);
	       		var element = '<div id="'+radom+'" class="slider" style="width:100%;"></div>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">滑块</label><div class="layui-input-block"><div class="v-c">' + element + '</div></div>'+tool+'</div>';
	       		break;
	       	case "dateRange":
	       		//日期范围
	       		var element = '<input type="text" class="layui-input lay-date">';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">日期范围</label><div class="layui-input-inline">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "date":
	       		//日期
	       		var element = '<input type="text" class="layui-input lay-date">';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">日期</label><div class="layui-input-inline">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "time":
	       		//时间
	       		var element = '<input type="text" class="layui-input lay-time">';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">时间</label><div class="layui-input-inline">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "editor":
	       		//编辑器
	       		var radom = Math.ceil(Math.random() * 100000);
	       		var element = '<textarea id="editor'+radom+'" class="editor" style="display: none;"></textarea>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">编辑器</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "uploadImg":
	       		//图片上传
	       		var element = '<div class="upload-img single" id=""><div class="action"><i class="layui-icon layui-icon-upload-drag"></i><p>上传</p></div></div>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">图片上传</label><div class="layui-input-block">' + element + '</div>'+tool+'</div>';
	       		break;
	       	case "uploadFile":
	       		//附件
	       		var element = '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id=""><i class="layui-icon">&#xe67c;</i>上传文件</button>';
	        	str = '<div class="layui-form-item draggable ui-draggable dropped" data-type="'+id+'"><label class="layui-form-label">附件</label><div class="layui-input-block"><div class="v-c">' + element + '</div></div>'+tool+'</div>';
	       		break;
	       	case "gridLayout":
	       		//栅格布局
	        	str = '<div class="layui-form-item draggable ui-draggable dropped nestedSortables" data-type="'+id+'">'+
        			  '		<div class="layui-row layui-col-space20">'+
        			  '			<div class="layui-col-md6 column">'+
	        		  '				<div class="layout droppable"></div>'+
	        		  '				'+toolColumn+''+
        			  			'</div>'+
        			  '			<div class="layui-col-md6 column">'+
	        		  '				<div class="layout droppable"></div>'+
	        		  '				'+toolColumn+''+
        			  '			</div>'+
        			  '		</div>'+
        			  '		'+toolRow+''+
        			  '</div>';
	       		break;
	    }
	    return str;
	}

	//click add form component
	$('.fc-components-list li').click(function(){
		console.log('%c 点击添加组件','color:LimeGreen')
		var type = $(this).data('type');
		var componentsWrap = $('#form-designer');
		var isActiveComponent = componentsWrap.find('.layui-form-item.active');
		var isActiveCloumn = componentsWrap.find('[data-type="gridLayout"] .active');

		//隐藏空结构
		componentsWrap.next('.empty').hide();

		if(isActiveComponent.length > 0) {
			//表单框中已存在组件，在该元素之后插入新组件
			$(components(type)).insertAfter(isActiveComponent).addClass('active').siblings().removeClass('active');
		}else if(isActiveCloumn.length > 0) {
			//当前位置是栅格布局内容器，在该容器内容插入组件
			isActiveCloumn.removeClass('active');
			$(components(type)).appendTo(isActiveCloumn.children('.layout')).addClass('active').siblings().removeClass('active');
			isActiveCloumn.attr('full','');
		}else{
			//表单框中是空的
			$(components(type)).appendTo(componentsWrap).addClass('active').siblings().removeClass('active');
		}
		//渲染组件
		form.render();
		element.init();
		fcInputNumber.render();

	    //渲染 评分
	    if(type == 'rate') {
	    	var id = $('#form-designer .active').find('.rate').attr('id');
		    rate.render({
	      		elem: '#'+id
		    });
	    }

	    //渲染 滑块
	    if(type == 'slider') {
	    	var id = $('#form-designer .active').find('.slider').attr('id');
			slider.render({
				elem: '#'+id,
				theme:'#1E9FFF',
			});	
	    }

	     //建立编辑器
	    if(type == 'editor') {
	    	var id = $('#form-designer .active').find('.editor').attr('id');
	    	layedit.build(id,{
	    		height: 180
	    	});
	    }
    
	    //级联选择器
	    if(type == 'cascader') {
	    	var id = $('#form-designer .active').find('.cascader').attr('id');
	        id =cascader({
	            elem: "#"+id,
	            data: [
	                {
	                    value: 'a',
	                    label: '选项一',
	                    children: [
	                        {
	                            value: 'AA1',
	                            label: 'aa1',
	                        },
	                        {
	                            value: 'BB1',
	                            label: 'bb1'
	                        }
	                    ]
	                },
	            ],
	            // url: "/aa",
	            // type: "post",
	            // triggerType: "change",
	            // showLastLevels: true,
	            // where: {
	            //     a: "aaa"
	            // },
	            // value: ["B", "BB2", "BBB4"],
	            // changeOnSelect: true,
	            // canParentSelect:true,
	            success: function (valData,labelData) {
	                console.log(valData,labelData);
	            }
	        });
	    }

	    if(type == 'gridLayout') {
	    	$('#form-designer [data-type="gridLayout"].active .droppable').sortable().disableSelection();
	    	//nestedSortables();
	    }
	})

	//拖拽添加组件
	var setup_draggable = function() {
		$( ".draggable" ).draggable({
		    connectToSortable: ".droppable",
		    helper: "clone",
		    zIndex:100,
		}).disableSelection();

		$( ".droppable" ).sortable({
		    accept: '.draggable',
		    connectWith: '.droppable',
		    receive: function (event, ui) {   
		    	console.log(ui)   
		        var $orig = $(ui.helper);
		        var type = $orig.data('type');
		        console.log('end')
		        $(this).find('.active').removeClass('active');
		        $(this).find('li[data-type="'+type+'"]').replaceWith($(components(type)).addClass('active'));
				//隐藏空结构
				$(this).next('.empty').hide();		        
				//渲染组件
				form.render();
				element.init();
				fcInputNumber.render();
		        $('.droppable').sortable();
		    },
		    over:function(event,ui) {
		    	console.log('eeeee')
		    }
		}).disableSelection();
	};
	setup_draggable();





// var	components1 = document.getElementById('components-list-1');
// var	components2 = document.getElementById('components-list-2');

// new Sortable(components1, {
// 	group: {
// 		name: 'nested',
// 		pull: 'clone',
// 		put: false
// 	},
// 	sort: false,
// });
// new Sortable(components2, {
// 	group: {
// 		name: 'nested',
// 		pull: 'clone',
// 		put: false
// 	},
// 	sort: false,
// });

// function nestedSortables() {
// 	// Nested demo
// 	var nestedSortables = [].slice.call(document.querySelectorAll('.nested-sortable'));
// 	console.log(nestedSortables[1])
// 	// 循环遍历每个嵌套的可排序元素
// 	for (var i = 0; i <nestedSortables.length; i++) { 
// 		new Sortable(nestedSortables[i], { 
// 			group: 'nested', 
// 			animation: 150, 
// 			fallbackOnBody: true, 
// 			swapThreshold: 0.65,
// 			// forceFallback: true,
// 	        onAdd: function (evt) {
// 	        	console.log('%c 拖拽添加组件','color:LimeGreen')
// 	        	console.log($(evt.to)[0])
// 	        	var type = $(evt.item).data('type');
// 		        $(evt.to).find('.active').removeClass('active');
// 		        $(evt.to).find('li[data-type="'+type+'"]').replaceWith($(components(type)).addClass('active'));

// 	        },
// 	        onUpdate: function (evt) {
// 	        	console.log('%c 组件排序变化','color:yellow')
// 	        	console.log(evt)
// 	        },
// 	        onEnd:function(evt) {
// 	        	console.log('end')
// 		        new Sortable($(evt.to)[0],{
// 		        	group: 'nested', 
// 		        	animation: 150,
// 		        	fallbackOnBody: true, 
// 					swapThreshold: 0.65,
// 		        })

// 	        }
// 		}); 
// 	}

// }
// nestedSortables();













	//components tool event
	util.event('lay-components',{
		copy:function() {
			console.log('copy component')

		},
		del:function() {
			console.log('%c删除组件','color:red')

			var type = $(this).data('type');

			//判断是删除布局 或 组件，column:栅格布局
			if(type == 'column') {
				//栅格布局删除
				var that = $(this).parents('.column');
				if(that.next().length > 0) {
					that.next().addClass('active');
					that.remove();
				}else if(that.prev().length > 0){
					that.prev().addClass('active');
					that.remove();
				}else if(that.parents('.layui-form-item').next().length > 0){
					that.parents('.layui-form-item').next().addClass('active');
					that.parents('.layui-form-item').remove();
				}else{
					that.parents('.layui-form-item').prev().addClass('active');
					that.parents('.layui-form-item').remove();
				}
			}else{
				//普通组件删除
				var that = $(this).parents('.layui-form-item.active');
				if(that.next().length > 0) {
					that.next().addClass('active');
				}else if(that.prev().length > 0) {
					that.prev().addClass('active');
				}else{
					that.parents('.column').removeAttr('full');
				}
				that.remove();
			}

			//表单中组件都删除了，显示空结构			
			if($('#form-designer').children().length === 0) {
				$('#form-designer').next('.empty').show();
			}
		}
	})

	//components click event && display the settings
	$(document).on('click','#form-designer .layui-form-item',function(e) {
		// console.log(e.target)

		//如果点击的是组件操作按钮icon，停止切换
		if($(e.target).is('i')) {
			return false;
		}

		//栅格布局中点击切换
		if($(e.target).is('.column')) {
			$(this).parents('.layui-form').find('div.active').removeClass('active');
			$(e.target).addClass('active');
			return false;
		}

		//栅格布局中点击组件
		if($(e.target).is('.tool')) {
			$(this).parents('.layui-form').find('div.active').removeClass('active');
			$(e.target).parent().addClass('active');
			return false;
		}

		//选择当前组件
		$(this).parents('.layui-form').find('[data-type="gridLayout"] div.active').removeClass('active');
		$(this).addClass('active').siblings().removeClass('active');
	})




})
